<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Blovex4\Logic;

/**
 * 数据库配置项业务逻辑
 * @author derek <693472824@qq.com>
 */
class ConfigLogic extends BaseLogic {
    
    /**
     * 取数据库 config 表配置项 
     * @return array    $config  返回数据库中配置项  array(key->value)
     * @author derek <693472824@qq.com>
     */
    public function getList(){
        
        $map = array('config_status'=>'1');
        
        $data   = M('Config')->where($map)->field('config_name, config_type, config_value')->select();
        
        $config = array();
        if($data && is_array($data)){
            foreach ($data as $value) {
                $config[$value['config_name']] = $this->parse($value['config_type'], $value['config_value']);
            }
        }
        return $config;
    }
    
    /**
     * 根据配置类型解析配置
     * @param  integer $type  配置类型
     * @param  string  $value 配置值
     * @author derek <693472824@qq.com>
     */
    private function parse($type, $value){
        switch ($type) {
            case 3: //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if(strpos($value,':')){
                    $value  = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k]   = $v;
                    }
                }else{
                    $value = $array;
                }
                break;
        }
        return $value;
    }
    
    /**
     * 添加配置项
     * @author derek <693472824@qq.com>
     */
    public function addConfig(){
        $configModel = D('Config');
        if($configModel->create()){
            $result = $configModel->add();
            if($result){
                S('DB_CONFIG_DATA',null);
            }
            return $result;
        }else{
            $this->error = $configModel->getError();
            return false;
        }
    }
    
    /**
     * 修改配置项
     * @author derek <693472824@qq.com>
     */
    public function editConfig(){
        
        $param = I();
        if(empty($param) || !is_array($param)){
            return true;
        }
        
        $configModel = D('Config');
        
        foreach ($param as $key=>$value){
            $map['config_name'] = $key;
            $result = $configModel->where($map)->setField('config_value', $value);
            if($result === false){
                return false;
            }
        }
        
        S('DB_CONFIG_DATA',null);
        return true;
    }
    
}

?>